#Requires -Version 7.0
<#
.SYNOPSIS
Automatically checks for and installs PowerShell 7 updates
.DESCRIPTION
Checks GitHub for the latest PowerShell 7 release and upgrades if newer than current version
.NOTES
Run with admin/sudo privileges:
Windows: Run as Administrator
Linux/macOS: Run with sudo
#>

# Check for elevation
$isElevated = $false
if ($IsWindows) {
    $currentPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
    $isElevated = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
} 
else {
    $isElevated = (id -u) -eq 0
}

if (-not $isElevated) {
    Write-Error "This script must be run as administrator/root. Aborting."
    exit 1
}

# Get current PS version
$currentVersion = $PSVersionTable.PSVersion.ToString()
Write-Host "Current PowerShell version: $currentVersion" -ForegroundColor Cyan

# Get latest release from GitHub
$latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/PowerShell/PowerShell/releases/latest" `
    -Headers @{'Accept' = 'application/vnd.github.v3+json'} `
    -ErrorAction Stop

$latestVersion = $latestRelease.tag_name.TrimStart('v')
Write-Host "Latest available version: $latestVersion" -ForegroundColor Cyan

# Compare versions
if ([System.Version]$currentVersion -ge [System.Version]$latestVersion) {
    Write-Host "Already on the latest version. No action needed." -ForegroundColor Green
    exit 0
}

# Platform-specific installation
Write-Host "Upgrading to v$latestVersion..." -ForegroundColor Yellow

if ($IsWindows) {
    # Windows installation
    $installScript = Join-Path $env:TEMP "install-powershell.ps1"
    Invoke-RestMethod "https://aka.ms/install-powershell.ps1" -OutFile $installScript
    & $installScript -UseMSI -Quiet -Preview:$($latestVersion -match 'preview')
}
elseif ($IsLinux) {
    # Debian/Ubuntu installation
    $packageName = if ($latestVersion -match 'preview') { 'powershell-preview' } else { 'powershell' }
    sudo apt-get update -qq
    sudo apt-get install --only-upgrade -y $packageName
}
elseif ($IsMacOS) {
    # macOS installation
    brew update
    if ($latestVersion -match 'preview') {
        brew upgrade powershell-preview
    } else {
        brew upgrade powershell
    }
}
else {
    Write-Error "Unsupported platform"
    exit 1
}

Write-Host @"
PowerShell upgraded to v$latestVersion successfully!

Please restart your shell:
1. Close this terminal
2. Open a new PowerShell session
3. Run: pwsh --version
"@ -ForegroundColor Green